package com.tuanzi.loan.business.service.family.impl;

import com.base.common.util.AESUtils;
import com.google.common.collect.Lists;
import com.google.gson.JsonObject;
import com.starbaba.model.utils.HttpConnectionUtils;
import com.starbaba.model.utils.JSONUtils;
import com.tuanzi.loan.business.constants.newcreditcard.CreditCardOrderStatus;
import com.tuanzi.loan.business.entity.family.LoanNewCreditCardOrder;
import com.tuanzi.loan.business.entity.family.LoanNewCreditCardRebate;
import com.tuanzi.loan.business.repository.family.LoanNewCreditCardOrderRepository;
import com.tuanzi.loan.business.repository.family.LoanNewCreditCardRebateRepository;
import com.tuanzi.loan.business.service.family.LoanNewCreditCardOrderService;
import com.tuanzi.loan.core.aspect.Debug;
import com.tuanzi.loan.core.service.CommonServiceImpl;
import com.tuanzi.loan.core.vo.PageSearcher;
import com.tuanzi.loan.vo.request.family.LoanNewCreditCardOrderRequest;
import com.tuanzi.loan.vo.response.family.LoanNewCreditCardOrderResponse;
import com.tuanzi.server.loan_base.constant.LoanRedisKey;
import com.tuanzi.server.loan_base.util.SendEmail;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.retry.RetryException;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @author caiwanlin
 * @create 2018-09-13 14:01
 */
@Slf4j
@Debug
@Service
@Transactional
@Retryable(value = {RetryException.class})
public class LoanNewCreditCardOrderServiceImpl extends CommonServiceImpl<LoanNewCreditCardOrder, Long> implements LoanNewCreditCardOrderService {
    @Autowired
    private LoanNewCreditCardOrderRepository loanNewCreditCardOrderRepository;

    @Autowired
    private LoanNewCreditCardRebateRepository loanNewCreditCardRebateRepository;

    @Value("${new_credit_card_rebate_host}")
    private String url;

    @Value("${loan-wallet-add-balance-key}")
    private String AES_KEY;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @Override
    public Page<LoanNewCreditCardOrderResponse> list(PageSearcher<LoanNewCreditCardOrderRequest> pageSearcher) {
        return loanNewCreditCardOrderRepository.list(pageSearcher.getSearchCondition(), pageSearcher.getPageable());
    }

    @Override
    public void onImportRebate(List<LoanNewCreditCardRebate> rebateList) throws Exception {
        rebateList.forEach(e -> {
            Long cardId = e.getCardId();
            String mobnum = e.getMobnum().replace("*", "_");
            String username = e.getUsername().replace("*", "");
            List<LoanNewCreditCardOrder> list = loanNewCreditCardOrderRepository
                    .findByCardIdAndMobnumContainsAndUsernameStartsWith(cardId, mobnum, username);
            list.forEach(o -> {
                //当订单状态不是已返现时，改为已返现
                if (o.getOrderStatus() != CreditCardOrderStatus.SUCCESS.ordinal()) {
                    o.setOrderStatus(CreditCardOrderStatus.SUCCESS.ordinal());
                    o.setRebateTime(new Date());
                    this.saveOrUpdate(o);
                    //推送数据给钱包中心
                    Long userId = o.getUserId();
                    Double rebateAmount = o.getRebateAmount();
                    String remark = "信用卡返现奖励";
                    JsonObject request = new JsonObject();
                    request.addProperty("userId", userId);
                    request.addProperty("amount", rebateAmount);
                    request.addProperty("remark", remark);
                    log.info("==新版信用卡提现请求参数："+request.toString());
                    String encrypt = AESUtils.encrypt(JSONUtils.toJsonString(request), AES_KEY);
                    String response = HttpConnectionUtils.connection(url, HttpConnectionUtils.POST, encrypt);
                    log.info("==新版信用卡提现响应参数："+response);
                    JsonObject jsonObject = JSONUtils.toJsonObject(response);
                    int code = jsonObject.get("code").getAsInt();
                    if (code == -1 && !url.contains("test.xmiles.cn")){
                        SendEmail.sendEmail(Lists.newArrayList("dkzjdev@xmiles.cn", "api_warning@xmiles.cn", "dkyunying@xmiles.cn"),
                                "新版信用卡导表推送返现金额到钱包中心",
                                " 申请记录：" + JSONUtils.toJsonString(o) + " 新版信用卡导表推送返现金额到钱包中心失败，状态码："+code);
                    }
                    else if (code == -2  && !url.contains("test.xmiles.cn")){
                        SendEmail.sendEmail(Lists.newArrayList("dkzjdev@xmiles.cn", "api_warning@xmiles.cn", "dkyunying@xmiles.cn"),
                                "新版信用卡导表推送返现金额到钱包中心",
                                " 申请记录：" + JSONUtils.toJsonString(o) + " 新版信用卡导表推送返现金额到钱包中心失败，状态码："+code);
                    }
                    //删除申请记录缓存
                    stringRedisTemplate.delete(String.format(LoanRedisKey.LOAN_NEW_CREDIT_CARD_ORDER_LIST,userId));

                }
            });
            loanNewCreditCardRebateRepository.save(e);

        });
    }

    @Override
    protected JpaRepository<LoanNewCreditCardOrder, Long> getRepository() {
        return loanNewCreditCardOrderRepository;
    }
}
